<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Common\ImgUploadController as ImgUpload;
use App\Repositories\Admin\PictureRepository;
use App\Repositories\Admin\RankRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redis;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;

class PictureController extends Controller
{
    protected $pictureRepository;
    protected $rankRepository;
    public function __construct(PictureRepository $pictureRepository)
    {
        $rankRepository = new RankRepository();
        $this->rankRepository = $rankRepository;
        $this->pictureRepository = $pictureRepository;
    }
    /**
     * 分页
     */
    public function page(Request $request){
        $number = $request->get('number');
        $result = $this->pictureRepository->page($number);
//        echo '<pre>';
        foreach ($result as $picture){
            echo $picture->picture_id;
            echo "__";
        }
        return $result->links();
    }

    /**
     * 图片分组更改
     */
    public function pictureCategoryChange(Request $request){
//        return json_encode($request->toArray());
        if($request->has('picture_id') && $request->has('picture_category_id')){
            $picture_id = $request->post('picture_id');
            $picture_category_id = $request->post('picture_category_id');
            $pictures = $this->pictureRepository->updatePicture($picture_id,['picture_category_id'=>$picture_category_id]);
            return json_encode($pictures);
        }else{
            return json_encode(['code'=>400,'msg'=>'传入参数有问题']);
        }
    }
    /**
     * 管理获取图片
     */
    public function getManagePictures(Request $request){
        $group = '';
        $orderby = '';
        if($request->has('group')){
            $group = $request->get('group');
        }
        if($request->has('orderby')){
            $orderby = $request->get('orderby');
        }
        if($request->has('pageNumber') && $request->has('page')&&$group !=''&&$orderby !=''){
            $pageNumber = $request->get('pageNumber');
            $page = $request->get('page');
            $pictures = $this->pictureRepository->getManagePicture($group,$orderby,$page,$pageNumber);
            return json_encode($pictures);
        }else{
            return json_encode(['code'=>400,'msg'=>'传入参数有问题']);
        }

    }
    /**
     * 审核图片，将审核结果更新到数据库
     */
    public function check(Request $request){
        $id = $request->get('picture_id');
        $check = $request->get('picture_check');
        $result = $this->pictureRepository->updateCheck($id,$check);
        if($result)
            return json_encode(['code'=>200,'picture_id'=>$id]);
        else
            return json_encode(['code'=>400,'picture_id'=>$id]);
    }
    /**
     * 多条件查询图片
     * axios应传入的参数格式为：
     * params:[
     *   {key:'picture_check',where:'=',value:0}
     *  ]
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $where = [];
        if($request->has('where')){
            $whereArr = $request->get('where');
            foreach ($whereArr as $key => $value){
                $value = json_decode($value,true);
                $where[] = [
                    $value['key'],
                    $value['where'],
                    $value['value']
                ];
            }
        }
        if($request->has('pageNumber')){
            $number = $request->get('pageNumber');
            $pictures = $this->pictureRepository->getByMorePage($where,$number);
        }else
            $pictures = $this->pictureRepository->getByMore($where);
        return json_encode($pictures);
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        header('Access-Control-Allow-Origin: *');
        if($request->has('user_id')&&$request->has('picture_category_id')&&$request->has('imageName')) {

            $user_id = $request->post('user_id');
            $picture_category_id = $request->post('picture_category_id');
            $imgName = $request->post('imageName');
            $rank = $this->rankRepository->getByTypeRankNumberStatus(2, 1, 1);
            $picture = [
                'picture_user_id' => $user_id,
                'picture_thumbnail' => $imgName,
                'picture_category_id' => $picture_category_id,
                'picture_health_point' => Redis::get('pictureBloode'),
                'picture_rank_number' => 0,
                'picture_uprank_type' => $rank->rank_condition_type,
                'picture_uprank_condition' => $rank->rank_condition,
            ];

            $picture = $this->pictureRepository->createPicture($picture);
            if ($picture) {
                if (Redis::exists('pictureNumber')) {
                    $pictureNumber = Redis::get('pictureNumber');
                    $pictureNumber++;
                    Redis::set('pictureNumber', $pictureNumber);
                } else {
                    Redis::set('pictureNumber', 1);
                }
                //今日新增图片
                if (Redis::exists('dayPictureNumber')) {
                    $dayPictureNumber = Redis::get('dayPictureNumber');
                    $dayPictureNumber++;
                    Redis::set('dayPictureNumber', $dayPictureNumber);
                } else {
                    Redis::set('dayPictureNumber', 1);
                }
                //今日各分组新增图片
                if (Redis::exists('dayPictureCategoryId_'.$picture_category_id)) {
                    $dayPictureCategoryIdNumber = Redis::get('dayPictureCategoryId_'.$picture_category_id);
                    $dayPictureCategoryIdNumber++;
                    Redis::set('dayPictureCategoryId_'.$picture_category_id, $dayPictureCategoryIdNumber);
                } else {
                    Redis::set('dayPictureCategoryId_'.$picture_category_id, 1);
                }
                return json_encode(['code' => 200, 'picture_id' => $picture->picrure_id]);
            } else {
                return json_encode(['code' => 400]);
            }
        }else{
            return json_encode(['code' => 400,'msg'=>'上传文件错误']);
        }

    }
    public function delPicture(Request $request)
    {
        if($request->has('picture_id')){
            $id = $request->post('picture_id');
            $fileName = $request->post('fileName');
            $qiniuResult = $this->qiniuDelete($fileName);
            $pictures = $this->pictureRepository->delPicture($id);
            if($pictures)
                return json_encode(['code'=>200,'msg'=>'删除成功','qiniu'=>$qiniuResult]);
            else
                return json_encode(['code'=>400,'msg'=>'删除失败','qiniu'=>$qiniuResult]);
        }else
            return json_encode(['code'=>400,'msg'=>'传参有问题']);
    }

    /**
     * @ 七牛删除文件
     */
    public function qiniuDelete($fileName){
        if($fileName) {
            $accessKey = config('qiniu.accessKey');
            $secretKey = config('qiniu.secretKey');
            $bucket = config('qiniu.bucket');

            $auth = new Auth($accessKey, $secretKey);
            $bucketManager = new BucketManager($auth);
            $err = $bucketManager->delete($bucket, $fileName);
            if ($err) {
                return ['code'=>200,'msg'=>'删除七牛文件成功','err'=>$err];
            }
        }else{
            return ['code'=>400,'msg'=>'没有fileName参数'];
        }

    }
}
